package com.tuanzi.loan.web.bean.settlement;

import com.base.common.log.LogService;
import com.google.common.collect.Lists;
import com.tuanzi.loan.business.constants.settlement.CompanyCooperationMode;
import com.tuanzi.loan.business.constants.settlement.SettlementType;
import com.tuanzi.loan.business.entity.family.ProductInfo;
import com.tuanzi.loan.business.entity.settlement.CompanyInfo;
import com.tuanzi.loan.business.entity.settlement.JfSltBackData;
import com.tuanzi.loan.business.entity.system.Dictionary;
import com.tuanzi.loan.business.service.family.ProductInfoService;
import com.tuanzi.loan.business.service.settlement.CompanyInfoService;
import com.tuanzi.loan.business.service.settlement.JfBackDataService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.core.exception.SystemException;
import com.tuanzi.loan.web.configuration.JSFWorkflowBean;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.event.RowEditEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.tuanzi.loan.business.constants.DictionaryCode.*;

@Data
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class JfBackDataBean extends JSFWorkflowBean<JfSltBackData> /*JSFInfoBean<JfSltBackData>*/ {

	@Autowired
	private JfBackDataService jfBackDataService;
	@Autowired
	private CompanyInfoService companyInfoService;

	@Autowired
	private ProductInfoService productInfoService;

	private List<JfSltBackData> jfSltBackDataList;
	private CompanyInfo companyInfo;
	private String fileUrl;
	private Long companyId;
	private List<String> productNames;

	@PostConstruct
	public void init() {
		String businessKey = task.getBusinessKey();
		String[] split = businessKey.split(":");
		companyId=Long.valueOf(split[1]);
		$ = new JfSltBackData();
		$.setType(0);
		jfSltBackDataList = jfBackDataService.findJfSltBackDataListByProcInstIdAndType(task.getProcInstId(), SettlementType.DAY.getIndex());
		fileUrl = jfBackDataService.getCurWeekPingZhengUrlByList(jfSltBackDataList);
		companyInfo = companyInfoService.findOne(companyId);
		List<ProductInfo> productInfoList = productInfoService.listAllProductInfoByCompanyId(companyId);
		productNames = productInfoList.parallelStream().map(pro->{
			return pro.getName();
		}).collect(Collectors.toList());
	}

	/**
	 * 文件上传操作
	 * 
	 * @param event
	 */
	public void fileUpload(FileUploadEvent event) {
		String url = this.uploadImg(event.getFile());
		this.fileUrl = url; // 刷新图片地址
		// 更新List中的图片地址
		for (JfSltBackData jfSltBackData : jfSltBackDataList) {
			jfSltBackData.setPzUrl(url);
		}

		FacesMessage message = new FacesMessage("上传成功！", event.getFile().getFileName() + " 上传成功。");
		FacesContext.getCurrentInstance().addMessage(null, message);
	}

	public void onTypeValueChange() {
		this.jfSltBackDataList = jfBackDataService.findJfSltBackDataListByProcInstIdAndType(task.getProcInstId(),$.getType());
		fileUrl = jfBackDataService.getCurWeekPingZhengUrlByList(jfSltBackDataList);
	}

	/**
	 * 增加结算数据
	 */
	public void addJfBackData() {
		JfSltBackData jfSltBackData = jfBackDataService.createJfSltBackData($.getType(), companyId, companyInfo.getCopMode());
		jfSltBackData.setProcInstId(task.getProcInstId());
		jfSltBackDataList.add(jfSltBackData);
	}

	/**
	 * 保存操作
	 */

	public void saveJfBackData(){
		//判空验证
		try {
			checkBaseMessage(companyInfo);
		} catch (Exception e) {
			addErrorMessage(e.getMessage());
			return;
		}
		//是否选择开发票
		changeInvoice(companyInfo);
		for (JfSltBackData jfSltBackData : jfSltBackDataList) {
			jfSltBackData.setPzUrl(fileUrl);
		}
		jfBackDataService.saveOrUpdate(jfSltBackDataList);
		jfBackDataService.saveUvRecord(jfSltBackDataList);
		companyInfoService.saveOrUpdate(companyInfo);

		addSuccessfullyMessage();
	}

	/**
	 * 提交
	 */
	public void onCommit() {
		//判空验证
		try {
			checkBaseMessage(companyInfo);
		} catch (Exception e) {
			addErrorMessage(e.getMessage());
			return;
		}
		//是否选择开发票
		changeInvoice(companyInfo);
		for (JfSltBackData data : jfSltBackDataList) {
			data.setIsEdit(0); // 设置为不可编辑状态
			data.setPzUrl(fileUrl);
		}
		jfBackDataService.saveOrUpdate(jfSltBackDataList);
		jfBackDataService.saveUvRecord(jfSltBackDataList);
		companyInfoService.saveOrUpdate(companyInfo);
		addSuccessfullyMessage();
	}

	/**
	 * 行编辑修改
	 */
	public void onRowEdit(RowEditEvent event) {
		JfSltBackData jfSltBackData = (JfSltBackData) event.getObject();
		this.jfSltBackDataList = jfBackDataService.updateJSBDListNotInDataBase(jfSltBackDataList, jfSltBackData, companyInfo);
		addSuccessfullyMessage();
	}
	/**
	 * 编辑修改取消操作
	 */
	public void onRowCancel() {
		FacesMessage msg = new FacesMessage("编辑", "取消成功");
		FacesContext.getCurrentInstance().addMessage(null, msg);
	}
	/*
	* 删除操作
	* */
	public void onRowDelete(RowEditEvent event) {
		//获取到缓存中的选中行的对象
		JfSltBackData jfSltBackData = (JfSltBackData) event.getObject();
		//删除集合中的对象
		jfSltBackDataList.remove(jfSltBackData);
		//通过行对象查看是否存在id 如果存在那么数据库中存在数据否则为缓存中数据
		if(jfSltBackData.getId()!=null){
			LogService.info("删除数据库中对象");
			jfBackDataService.deletebyid(jfSltBackData.getId());
		}
		FacesMessage msg = new FacesMessage("删除", "删除成功");
		FacesContext.getCurrentInstance().addMessage(null, msg);
	}

	public void addMessage(String summary, String detail) {
		FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, summary, detail);
		FacesContext.getCurrentInstance().addMessage(null, message);
	}
	public void onChangeStlMoney(JfSltBackData jfSltBackData){
		Integer copMode = companyInfo.getCopMode();
		Float settlementPriceCpa = companyInfo.getSettlementPriceCpa();
		Float settlementPriceCps = companyInfo.getSettlementPriceCps();
		Integer registerNum = jfSltBackData.getRegisterNum();
		Double lendMoney = jfSltBackData.getLendMoney();
		Integer clickNum = jfSltBackData.getClickNum();
		double sltMoney = 0;
		if (CompanyCooperationMode.CPA.getIndex()==copMode){
			if (registerNum != null){
				sltMoney = registerNum*settlementPriceCpa;
				jfSltBackData.setSltMoney(sltMoney);
			}
			else {
				jfSltBackData.setSltMoney(null);
			}
		}
		else if (CompanyCooperationMode.CPS.getIndex() == copMode){
			if (lendMoney != null){
				sltMoney = lendMoney*settlementPriceCps/100;
				jfSltBackData.setSltMoney(sltMoney);
			}
			else {
				jfSltBackData.setSltMoney(null);
			}
		}
		else if (CompanyCooperationMode.CPC.getIndex() == copMode){
			if (clickNum != null){
				sltMoney = clickNum*settlementPriceCpa;
				jfSltBackData.setSltMoney(sltMoney);
			}
			else {
				jfSltBackData.setSltMoney(null);
			}
		}
		else if (CompanyCooperationMode.CPA_CPS.getIndex() == copMode){
			if (registerNum != null && lendMoney != null){
				sltMoney = (registerNum*settlementPriceCpa)+(lendMoney*settlementPriceCps/100);
				jfSltBackData.setSltMoney(sltMoney);
			}
			else {
				jfSltBackData.setSltMoney(null);
			}
		}
	}

	/**
	 * 日期改变查询参与uv
	 */
	public void dateChange(){

		Calendar calendar = Calendar.getInstance();
		calendar.set(2018,0,26,0,0,0);
		Date time = calendar.getTime();
//		Integer integer = jfBackDataService.countProductClickUv(time, companyId);
//		System.out.println(integer);
	}

	// 改变我司收款账户
	public void onChangeReceiveAccount() {
		String receivableAccount = companyInfo.getReceivableAccount();
		Map<String, List<Dictionary>> dictionaries = getDictionaries();
		List<Dictionary> dictionaryList = dictionaries.get(SETTLEMENT_RECEIVE_ACCOUNT);
		dictionaryList.forEach(dic -> {
			String account = dic.getValue1();
			if (account.equals(receivableAccount)) {
				companyInfo.setReceivableCardNumber(dic.getValue2());
			}
		});
	}

	// 改变我司收款账号
	public void onChangeReceiveAccountNumber() {
		String receivableCardNumber = companyInfo.getReceivableCardNumber();
		Map<String, List<Dictionary>> dictionaries = getDictionaries();
		List<Dictionary> dictionaryList = dictionaries.get(SETTLEMENT_RECEIVE_ACCOUNT);
		dictionaryList.forEach(dic -> {
			String accountNumber = dic.getValue2();
			if (accountNumber.equals(receivableCardNumber)) {
				companyInfo.setReceivableAccount(dic.getValue1());
			}
		});
	}
	// 是否开发票
	public void changeInvoice(CompanyInfo companyInfo) {
		if (companyInfo.getIfInvoice() == false) {
			companyInfo.setInvoiceContent(null);
			companyInfo.setFirstPartyBank(null);
			companyInfo.setFirstPartyAccount(null);
			companyInfo.setFirstPartyCardNumber(null);
			companyInfo.setInvoiceAddress(null);
			companyInfo.setRecipientsName(null);
			companyInfo.setRecipientsMobile(null);
			companyInfo.setDeliveryAddress(null);
		} else {
			companyInfo.setPayer(null);
		}
	}

	//验证信息是否为空
	public void checkBaseMessage(CompanyInfo companyInfo) throws Exception{
		//公司信息
		if (StringUtils.isBlank(companyInfo.getContactName())) {
			throw new SystemException("公司信息[甲方商务姓名不能为空]");
		}
		if (StringUtils.isBlank(companyInfo.getContactPhone())) {
			throw new SystemException("公司信息[甲方商务电话不能为空]");
		}
		if (StringUtils.isBlank(companyInfo.getContactEmail())) {
			throw new SystemException("公司信息[甲方商务邮箱不能为空]");
		}
		if (StringUtils.isBlank(companyInfo.getFirstPartyAddress())) {
			throw new SystemException("公司信息[甲方实际办公地址不能为空]");
		}

		//发票信息
		if (companyInfo.getIfInvoice() == false) {
			if (StringUtils.isBlank(companyInfo.getPayer())) {
				throw new SystemException("开票信息[打款人姓名不能为空]");
			}
		} else {
			if (companyInfo.getInvoiceContent() == null) {
				throw new SystemException("开票信息[开票内容不能为空]");
			}
			if (StringUtils.isBlank(companyInfo.getFirstPartyBank())) {
				throw new SystemException("开票信息[甲方支行不能为空]");
			}
			if (StringUtils.isBlank(companyInfo.getFirstPartyAccount())) {
				throw new SystemException("开票信息[甲方银行账户不能为空]");
			}
			if (StringUtils.isBlank(companyInfo.getFirstPartyCardNumber())) {
				throw new SystemException("开票信息[甲方银行卡号不能为空]");
			}
			if (StringUtils.isBlank(companyInfo.getInvoiceAddress())) {
				throw new SystemException("开票信息[开票地址不能为空]");
			}
			if (StringUtils.isBlank(companyInfo.getRecipientsName())) {
				throw new SystemException("开票信息[收件人姓名不能为空]");
			}
			if (StringUtils.isBlank(companyInfo.getRecipientsMobile())) {
				throw new SystemException("开票信息[收件人手机号不能为空]");
			}
			if (StringUtils.isBlank(companyInfo.getDeliveryAddress())) {
				throw new SystemException("开票信息[收件详细地址不能为空]");
			}
		}
	}

	@Override
	protected List<String> getDictionaryCodes() {
		return Lists.newArrayList(SETTLEMENT_CYCLE, APPROVAL_TYPE, COOPERATION_MODE, COMPANY_BACKGROUND, SETTLEMENT_BILLING_CONTENT, SETTLEMENT_SPREAD_CHANNEL,SETTLEMENT_RECEIVE_ACCOUNT);
	}

	@Override
	public void onSave() {
		saveJfBackData();
	}

	@Override
	public void validate() {

	}
}
